package lex.mtd.ui;

import java.awt.BorderLayout;

import javax.swing.JScrollPane;
import javax.swing.JSplitPane;

import org.lex.swing.ContainerFactory;

import lex.mtd.Download;
import lex.mtd.core.DownloadManager;
import lex.mtd.core.DownloadObject;
import lex.mtd.ui.details.DetailsPane;
import lex.mtd.ui.download.DwonloadTable;

public class MainContentPane extends javax.swing.JPanel {
	private JSplitPane mainSplitPane;
	private JSplitPane downloadAreaSplitPane;
	// =====================================
	private CategoryTree categoryTree = null;
	private DwonloadTable downloadTable = null;
	private DetailsPane detailsPane = null;
	private StatusPane statusPane = null;

	public MainContentPane() {
		super();
		initialize();
		this.hookReloadTimer();
	}

	public void addDownloadTask(DownloadObject task) {
		DownloadManager dm = new DownloadManager(task, Download.getApplication().getLogSet());
		this.getDownloadTable().addDownloadManager(dm);
	}

	private CategoryTree getCategoryTree() {
		if (null == categoryTree)
			categoryTree = new CategoryTree();
		return categoryTree;
	}

	public DwonloadTable getDownloadTable() {
		if (null == downloadTable)
			downloadTable = new DwonloadTable();
		return downloadTable;
	}

	public DetailsPane getDetailsPane() {
		if (null == detailsPane)
			detailsPane = new DetailsPane();
		return detailsPane;
	}

	private void hookReloadTimer() {
		ReloadService service = ReloadService.getService();
		service.add(this.getDownloadTable());
		service.add(this.getDetailsPane());
	}

	private void initialize() {
		this.setLayout(new BorderLayout());
		this.add(new MainToolBar(), BorderLayout.NORTH);
		this.add(getMainSplitPane(), BorderLayout.CENTER);
		this.add(getStatusPane(), BorderLayout.SOUTH);
	}

	private JSplitPane getMainSplitPane() {
		if (mainSplitPane == null) {
			mainSplitPane = ContainerFactory.createBorderlessSplitPane();
			mainSplitPane.setName(getClass().getName() + ".main");
			mainSplitPane.setResizeWeight(0.2);
			mainSplitPane.setDividerSize(5);
			mainSplitPane.setLeftComponent(new JScrollPane(getCategoryTree()));
			mainSplitPane.setRightComponent(getDownloadAreaSplitPane());
		}
		return mainSplitPane;
	}

	private JSplitPane getDownloadAreaSplitPane() {
		if (downloadAreaSplitPane == null) {
			downloadAreaSplitPane = ContainerFactory.createBorderlessSplitPane();
			downloadAreaSplitPane.setName(getClass().getName() + ".download");
			downloadAreaSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
			downloadAreaSplitPane.setDividerSize(5);
			downloadAreaSplitPane.setResizeWeight(0.4);
			downloadAreaSplitPane.setTopComponent(new JScrollPane(getDownloadTable()));
			downloadAreaSplitPane.setBottomComponent(getDetailsPane());
		}
		return downloadAreaSplitPane;
	}

	private StatusPane getStatusPane() {
		if (null == statusPane)
			statusPane = new StatusPane();
		return statusPane;
	}
}
